package com.itheima.stock.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.itheima.stock.constant.Constants;
import com.itheima.stock.entity.StockBlockRtInfo;
import com.itheima.stock.entity.StockBusiness;
import com.itheima.stock.entity.StockMarketIndexInfo;
import com.itheima.stock.entity.StockRtInfo;
import com.itheima.stock.mapper.StockBlockRtInfoMapper;
import com.itheima.stock.mapper.StockBusinessMapper;
import com.itheima.stock.mapper.StockMarketIndexInfoMapper;
import com.itheima.stock.mapper.StockRtInfoMapper;
import com.itheima.stock.properties.MarketIndexProperties;
import com.itheima.stock.service.StockTimerTaskService;
import com.itheima.stock.util.IdWorkers;
import jakarta.servlet.http.HttpServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class StockTimerTaskServiceImpl implements StockTimerTaskService {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private StockMarketIndexInfoMapper stockMarketIndexInfoMapper;

    @Autowired
    private MarketIndexProperties marketIndexProperties;
    @Autowired
    private IdWorkers idWorkers;
    @Autowired
    private StockBusinessMapper stockBusinessMapper;

    @Autowired
    private StockRtInfoMapper stockRtInfoMapper;
    @Autowired
    private StockBlockRtInfoMapper blockRtInfoMapper;

    @Override
    public void getBlockInfo() {
        String url = "https://vip.stock.finance.sina.com.cn/q/view/newSinaHy.php";
        HttpMethod method = HttpMethod.GET;
        HttpHeaders header = new HttpHeaders();
        header.add("referer", "https://finance.sina.com.cn/stock/");
        header.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36");
        HttpEntity<?> entity = new HttpEntity<>(header);
        ResponseEntity<String> response = restTemplate.exchange(url, method, entity, String.class);
        //用正则表达式解析数据,转换成StockMarketIndexInfo
        String responseBody = response.getBody();
        String reg = "var S_Finance_bankuai_sinaindustry = (.+)";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(responseBody);
        List<StockBlockRtInfo> infos = Lists.newArrayList();
        while(matcher.find()) {
            String jsonStr = matcher.group(1);
            Map map = JSON.parseObject(jsonStr, Map.class);
            Collection values = map.values();
            values.forEach(e-> {
                String str = (String) e;
                String[] split = str.split(",");
                String label = split[0];
                String blockName = split[1];
                String companyNum = split[2];
                String avgPrice = split[3];
                String updownRate = split[5];
                String tradeAmount = split[6];
                String tradeVolume = split[7];
                StockBlockRtInfo info = StockBlockRtInfo.builder()
                        .id(idWorkers.nextStrId())
                        .label(label)
                        .blockName(blockName)
                        .companyNum(Integer.parseInt(companyNum))
                        .avgPrice(new BigDecimal(avgPrice))
                        .updownRate(new BigDecimal(updownRate))
                        .tradeAmount(Long.parseLong(tradeAmount))
                        .tradeVolume(Long.parseLong(tradeVolume))
                        .curTime(LocalDateTime.now())
                        .build();
                        infos.add(info);
            });
            blockRtInfoMapper.insertBatch(infos);
        }
    }

    @Override
    public void getStockRtIndex() {
        //爬数据
        List<StockBusiness> secCodes = stockBusinessMapper.selectAll();
        List<String> list = secCodes.stream().map(e -> {
            if (e.getSecCode().startsWith("000")) {
                return "sz" +  e.getSecCode();
            } else if (e.getSecCode().startsWith("600")) {
                return "sh" +  e.getSecCode();
            } else {
                return null;
            }
        }).toList();
        String urlPrefix = "https://hq.sinajs.cn/list";
        String codeString = String.join(",", list);
        String url = String.join("=", urlPrefix, codeString);
        HttpMethod method = HttpMethod.GET;
        HttpHeaders header = new HttpHeaders();
        header.add("referer", "https://finance.sina.com.cn/stock/");
        header.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36");
        HttpEntity<?> entity = new HttpEntity<>(header);
        ResponseEntity<String> response = restTemplate.exchange(url, method, entity, String.class);
        //用正则表达式解析数据,转换成StockRtInfo
        String responseBody = response.getBody();
        String reg = "var hq_str_[a-z][a-z](\\d.+)=\"(.+)\";";
        Pattern compile = Pattern.compile(reg);
        Matcher matcher = compile.matcher(responseBody);
        List<StockRtInfo> infos = Lists.newArrayList();
        while(matcher.find()) {
            String secCode = matcher.group(1);
            String group = matcher.group(2);
            String[] split = group.split(",");
            String stockName = split[0];
            String openPrice = split[1];
            String preClosePrice = split[2];
            String curPrice = split[3];
            String maxPrice = split[4];
            String minPrice = split[5];
            String tradeAmount = split[8];
            double number = Double.parseDouble(tradeAmount);
            int intPart = (int) number;
            String tradeVolume = split[9];
            double number2 = Double.parseDouble(tradeVolume);
            int intPart2 = (int) number2;
            String date = split[30];
            String time = split[31];
            StockRtInfo info = StockRtInfo.builder()
                    .id(idWorkers.nextStrId())
                    .stockCode(secCode)
                    .stockName(stockName)
                    .openPrice(new BigDecimal(openPrice))
                    .preClosePrice(new BigDecimal(preClosePrice))
                    .curPrice(new BigDecimal(curPrice))
                    .maxPrice(new BigDecimal(maxPrice))
                    .minPrice(new BigDecimal(minPrice))
                    .tradeAmount((long) intPart)
                    .tradeVolume((long) intPart2)
                    .curTime(LocalDateTime.parse(date + " " + time, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                    .build();
            infos.add(info);
        }
        //插入数据库
        stockRtInfoMapper.insertBatch(infos);
    }

    @Override
    public void getInnerMarketInfo() {
        //爬数据
        List<String> inner = marketIndexProperties.getInner();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < inner.size(); i++) {
            if (i == inner.size() - 1) {
                stringBuilder.append(inner.get(i));
            } else {
                stringBuilder.append(inner.get(i)).append(',');
            }
        }
        String string = stringBuilder.toString();
        String url = "http://hq.sinajs.cn/list=" + string;
        HttpMethod method = HttpMethod.GET;
        HttpHeaders header = new HttpHeaders();
        header.add("referer", "https://finance.sina.com.cn/stock/");
        header.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36");
        HttpEntity<?> entity = new HttpEntity<>(header);
        ResponseEntity<String> response = restTemplate.exchange(url, method, entity, String.class);
        //用正则表达式解析数据,转换成StockMarketIndexInfo
        String responseBody = response.getBody();
        String reg = "var hq_str_(.+)=\"(.+)\";";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(responseBody);
        List<StockMarketIndexInfo> stockMarketIndexInfos = Lists.newArrayList();
        while (matcher.find()) {
            String code = matcher.group(1);
            String str = matcher.group(2);
            String[] split = str.split(",");
            String markName = split[0];
            String curPoint = split[1];
            String currentPrice = split[2];
            String updownRate = split[3];
            String tradeAccount = split[4];
            String tradeVolume = split[5];
            StockMarketIndexInfo info = StockMarketIndexInfo.builder()
                    .id(idWorkers.nextStrId())
                    .markId(code)
                    .markName(markName)
                    .curPoint(new BigDecimal(curPoint))
                    .currentPrice(new BigDecimal(currentPrice))
                    .updownRate(new BigDecimal(updownRate))
                    .tradeAccount(Long.valueOf(tradeAccount))
                    .tradeVolume(Long.valueOf(tradeVolume))
                    .curTime(LocalDateTime.now())
                    .build();

            if (stockMarketIndexInfos.size() > Constants.NUMBER_120) {
                stockMarketIndexInfoMapper.insertBatch(stockMarketIndexInfos);
                stockMarketIndexInfos.clear();
            }
            stockMarketIndexInfos.add(info);
        }
        //封装数据,写入数据库

    }
}
